namespace Testcontainers.Milvus;

public abstract class MilvusContainerTest : IAsyncLifetime
{
    private readonly MilvusContainer _milvusContainer;

    private MilvusContainerTest(MilvusContainer milvusContainer)
    {
        _milvusContainer = milvusContainer;
    }

    public async ValueTask InitializeAsync()
    {
        await _milvusContainer.StartAsync()
            .ConfigureAwait(false);
    }

    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore()
            .ConfigureAwait(false);

        GC.SuppressFinalize(this);
    }

    [Fact]
    [Trait(nameof(DockerCli.DockerPlatform), nameof(DockerCli.DockerPlatform.Linux))]
    public async Task GetVersionReturnsExpectedVersion()
    {
        // Given
        using var client = new MilvusClient(_milvusContainer.GetEndpoint());

        // When
        var version = await client.GetVersionAsync(TestContext.Current.CancellationToken)
            .ConfigureAwait(true);

        // Then
        Assert.EndsWith(version, _milvusContainer.Image.Tag);
    }

    protected virtual ValueTask DisposeAsyncCore()
    {
        return _milvusContainer.DisposeAsync();
    }

    [UsedImplicitly]
    public sealed class MilvusDefaultConfiguration : MilvusContainerTest
    {
        public MilvusDefaultConfiguration()
            : base(new MilvusBuilder(TestSession.GetImageFromDockerfile()).Build())
        {
        }
    }

    [UsedImplicitly]
    public sealed class MilvusSidecarConfiguration : MilvusContainerTest
    {
        public MilvusSidecarConfiguration()
            : this(new NetworkBuilder().Build())
        {
        }

        private MilvusSidecarConfiguration(INetwork network)
            : base(new MilvusBuilder(TestSession.GetImageFromDockerfile())
                .WithEtcdEndpoint("etcd:2379")
                .DependsOn(new ContainerBuilder("quay.io/coreos/etcd:v3.5.5")
                    .WithNetworkAliases("etcd")
                    .WithCommand("etcd")
                    .WithCommand("-advertise-client-urls=http://127.0.0.1:2379")
                    .WithCommand("-listen-client-urls=http://0.0.0.0:2379")
                    .WithCommand("-data-dir=/etcd")
                    .WithEnvironment("ETCD_AUTO_COMPACTION_MODE", "periodic")
                    .WithEnvironment("ETCD_AUTO_COMPACTION_RETENTION", "0")
                    .WithEnvironment("ETCD_QUOTA_BACKEND_BYTES", "0")
                    .WithEnvironment("ETCD_SNAPSHOT_COUNT", "100000")
                    .WithWaitStrategy(Wait.ForUnixContainer().UntilMessageIsLogged("ready to serve client requests"))
                    .DependsOn(network)
                    .Build())
                .DependsOn(network)
                .Build())
        {
        }
    }
}